import React, { useState } from 'react';
import { Container, Form, Button, Image } from 'react-bootstrap';
import { useNavigate } from 'react-router-dom';

const loginUrl = process.env.REACT_APP_LOGIN_URL;

const Login = () => {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const navigate = useNavigate();

  const handleSubmit = async (event) => {
    event.preventDefault();
    const response = await fetch(loginUrl, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });
    const data = await response.json();
    if (response.ok) {
      localStorage.setItem('token', data.token); // 存储JWT令牌
      navigate('/publish'); // 登录成功，跳转到发布页面
    } else {
      alert('认证失败: ' + data.error); // 显示错误信息
    }
  };

  return (
    <Container className="mt-5" style={{ textAlign: 'center' }}>
      <h1>登录</h1>
      <Image
        src={require('./logo.png')}
        alt="Logo"
        className="mx-auto d-block"
        style={{ maxWidth: '50%' }}
      />
      <Form onSubmit={handleSubmit} className="mt-4">
        <Form.Group controlId="loginUsername">
          <Form.Label>账号：</Form.Label>
          <Form.Control
            type="text"
            placeholder="请输入账号"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
        </Form.Group>
        <Form.Group controlId="loginPassword">
          <Form.Label>密码：</Form.Label>
          <Form.Control
            type="password"
            placeholder="请输入密码"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
        </Form.Group>
        <Button variant="primary" type="submit">
          登录
        </Button>
      </Form>
    </Container>
  );
};

export default Login;